# -*- coding:utf-8 -*-
__author__ = 'xigu007'
import kivy
kivy.require('1.9.0')
import os
os.environ['KIVY_NO_CONFIG']= 'true'
os.environ['KIVY_NO_FILELOG']= 'true'

from kivy.config import Config
from kivy.utils import platform

Config.set('graphics', 'maxfps', 60)
if platform == 'win' or platform == 'macosx':
    Config.set('graphics', 'height', 720)
    Config.set('graphics', 'width', 384)
Config.set('widgets', 'scroll_timeout', 1000)
Config.set('widgets', 'scroll_distance', 8)
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.metrics import dp, sp
from kivy.properties import StringProperty, ObjectProperty,ListProperty,NumericProperty
from composite_widget.base import RelativeComposite, Division
from composite_widget.content import LabelContent
from recycleview.recycleview import _kivy_1_9_1
from recycleview.staggered_layout import StaggeredViewMixin
from util_widget.floatlayer_scrollview import FloatLayerScrollView
from math import sin, pi
from kivy.core.text import LabelBase
from kivy.resources import resource_add_path
from kivy.uix.button import Button
from kivy.lang import Builder
LabelBase.get_system_fonts_dir()
resource_add_path('../fonts')
os.environ['KIVY_VALID_FONT'] = 'SourceHanSansCN-Regular.otf'

Builder.load_string('''
<BoxLayoutColor>
    canvas.before:
        Color:
            rgb: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size
<TransparentHeader>
    canvas:
        Color:
            rgb: (.4,.671,.925)
        Rectangle:
            pos: 0,0
            size: self.size
    LabelContent:
        text: '透明标题头'
        font_size: sp(16)

<PictureWidget>
    wrap_content_height: True
    ImageContent:
        id: pic
        source: './res/dog.jpg'
        size_hint: 1.0, None

<SplitView>
    canvas.before:
        Color:
            rgb: .91,.91,.91
        Rectangle:
            pos: 0,0
            size: self.size

<ItemTextView>
    canvas.before:
        Color:
            rgb: 1,1,1
        Rectangle:
            pos: 0,0
            size: self.size
        #背景分割线
        Color:
            rgb: 0.75,0.75,0.75
        Rectangle:
            pos: 0,0
            size: self.width,1
    contents_typesetting: 'anchor'
    ImageContent:
        source: root.icon
        size_hint: None, 0.45
        margin: dp(20),0,0,0
        anchor: 'left'
    LabelContent:
        text: root.text
        font_size: sp(15)
        color: 0.2,0.2,0.2,1.0
        margin: dp(10),0,0,0
        anchor: 'left'
    ImageContent:
        source: './res/arrow_normal.png'
        image_size: dp(20), None
        margin: 0,dp(15),0,0
        anchor: 'right'

<TransparentHeaderPage>:
    scroll_view: scroll_view
    container: container
    orientation: 'vertical'
    BoxLayout:
        id: container
        orientation: 'vertical'
        FloatLayerScrollView:
            id: scroll_view
    BoxLayout:
        size_hint_y: None
        height: dp(50)
        Button:
            text: 'button1'
            on_release: root.button1_click()
        Button:
            text: 'button2'
            on_release: root.button2_click()
''')

class BoxLayoutColor(BoxLayout):
    background_color = ListProperty([.91,.91,.91,1])

class TransparentHeader(RelativeComposite):
    def __init__(self,**kwargs):
        super(TransparentHeader,self).__init__(**kwargs)
        self.opacity = 0.0

class PictureWidget(RelativeComposite):
    def __init__(self,**kwargs):
        super(PictureWidget,self).__init__(**kwargs)
        self.size_hint_y = None
        pic = self.ids['pic']
        pic.transform = {'scale':{'x':1.0, 'y':1.0}, 'translate':{'x':0,'y':0}}

    def scale_move(self,scale, x, y):
        pic = self.ids['pic']
        pic.scale = (scale, scale)
        pic.translate = (x,y)

class TransparentPad(RelativeComposite,StaggeredViewMixin):
    def __init__(self,**kwargs):
        super(TransparentPad,self).__init__(**kwargs)
        self.size_hint_y = None

    def refresh_view_attrs(self, rv, data):
        self.height = data['height']

class SplitView(RelativeComposite,StaggeredViewMixin):
    def __init__(self,**kwargs):
        super(SplitView,self).__init__(**kwargs)
        self.size_hint_y = None
        self.height =dp(15)


class ItemTextView(RelativeComposite,StaggeredViewMixin):
    icon = StringProperty('')
    text = StringProperty('')

    def __init__(self,**kwargs):
        super(ItemTextView,self).__init__(**kwargs)
        self.size_hint_y = None
        self.height = dp(64)

    def refresh_view_attrs(self, rv, data):
        self.text = data['text']
        self.icon = data['icon']

s_items_data = [('res/home_icons/20160126194705meishi.png', '美食'),
    ('res/home_icons/20160126202805dianying.png', '电影'),
    ('res/home_icons/20160126203337jiudian.png', '酒店'),
    ('res/home_icons/20160126203103xiuxianyule.png', '休闲娱乐'),
    ('res/home_icons/20160126203251waimai.png', '外卖'),
    ('res/home_icons/20160204172927huoguo.png', '火锅'),
    ('res/home_icons/20160126202918liren.png', '丽人'),
    ('res/home_icons/20160126203440zhoubianyou.png', '周边游'),
    ('res/home_icons/20160126205426shenghuofuwu.png', '生活服务'),
    ('res/home_icons/20160126205135jingguan.png', '度假套餐')]

class TransparentHeaderPage(BoxLayoutColor):
    scroll_view = ObjectProperty(None)
    container = ObjectProperty(None)
    def __init__(self, **kwargs):
        self.header = None
        self.pic_pad = None
        self.pic_origin_height = 0
        super(TransparentHeaderPage,self).__init__(**kwargs)
        sv = self.scroll_view
        if sv:
            self.header = TransparentHeader(size_hint_y=None, height=dp(36))
            sv.add_widget_foreground(self.header)
            fbind = sv.fbind if _kivy_1_9_1 else sv.fast_bind
            fbind('on_layout', self.layout_header)
            fbind('on_scrolling', self.scrolling)
            effect_y = sv.scroll_view.effect_y
            effect_y.spring_constant = 2.0
            effect_y.edge_damping = 0.05

    def layout_header(self, *args):
        x,y,w,h = args[1:]
        header = self.header
        if header:
            header.x = x
            header.y = y + h - header.height
            header.width = w
        pic_pad = self.pic_pad
        if pic_pad:
            pic_pad.x = x
            pic_pad.y = y + h - 0.85*self.pic_origin_height
            pic_pad.width = w

    def scrolling(self, object, scroll, min, max, rv):
        header = self.header
        ref_scroll = min + dp(100)
        if scroll <= min + dp(30):
            header.opacity = 0.0
        elif scroll >= ref_scroll:
            header.opacity = 1.0
        else:
            header.opacity = float(scroll - min)/ dp(70)
        pic_pad = self.pic_pad
        if pic_pad:
            origin_height = self.pic_origin_height
            d = 0.4*origin_height
            if  scroll <= min - d:
                new_h = origin_height + min - d - scroll
                center_y = min + 0.35*origin_height
                cur_y = min + 0.5*new_h
                y = center_y - cur_y
                scale = float(new_h) / origin_height
                pic_pad.scale_move(scale, 0, y)
            elif scroll <= min:
                y = -0.375*(min - scroll)
                pic_pad.scale_move(1.0, 0, y)
            elif scroll <= min + d:
                y = -0.6*(min - scroll)
                pic_pad.scale_move(1.0, 0, y)

    def button1_click(self,*args):
        global s_items_data
        if self.pic_pad is None:
            pic_pad = self.pic_pad = PictureWidget()
            pic_pad.layout(0, ref_size=(self.width, None))
            self.pic_origin_height = pic_pad.height
            self.scroll_view.add_widget_background(pic_pad)
        data =[]
        i = 0
        data.append({'viewclass':'TransparentPad', 'height': 0.6*self.pic_origin_height if self.pic_pad else dp(180)})
        for j in range(2):
            for icon, text in s_items_data:
                i += 1
                if i % 3 == 0:
                   data.append({'viewclass':'SplitView'})
                data.append({'viewclass':'ItemTextView', 'icon':icon, 'text':text})
        rv = self.scroll_view.scroll_view
        rv.data = data
        self.data = data

    def button2_click(self,*args):
        pass

class MyApp(App):
    def build(self):
        root = TransparentHeaderPage()
        return root

MyApp().run()
